package com.neusoft.blog.config;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.neusoft.blog.bean.RespBean;
import com.neusoft.blog.bean.Userinfo;
import com.neusoft.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig_other extends WebSecurityConfigurerAdapter {//

@Autowired
UserService userService;
@Autowired
    CommonsAccessManage commonsAccessManage;
@Autowired
    CommonsFilter commonsFilter;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login");
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>(){
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(commonsFilter);
                        o.setAccessDecisionManager(commonsAccessManage);
                        return o;
                    }
                })
                .and()
                .formLogin()
                // 登录处理接口
                .loginProcessingUrl("/doLogin")
                // 定义登录页面，未登录时，访问一个需要登录之后才能访问的接口，会自动跳转到该页面
                .loginPage("/login")
                //定义登录时，用户名的 key，默认为 username
                .usernameParameter("username")
                //定义登录时，用户密码的 key，默认为 password
                .passwordParameter("password")
                //登录成功的处理器
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        //authentication 里面有登录信息
                        response.setContentType("application/json;charset=utf-8");

                        PrintWriter writer= response.getWriter();
                        Userinfo user = ((Userinfo) authentication.getPrincipal());//用户信息返回Object类型，要强转换未User类
                        user.setPassword(null);//强转user为了设置user里面的方法
                         RespBean ok = RespBean.ok(200,"登录成功",user);
                        writer.print(new ObjectMapper().writeValueAsString(ok)); //将对象写成json
                        writer.flush();
                        writer.close();
                    }

                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException, IOException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter writer= response.getWriter();
                        RespBean error=null;
                        if (e instanceof LockedException){
                            error=RespBean.error(500,"对不起,您的用户被锁定,请联系管理员");
                        }else if (e instanceof DisabledException){
                            error=RespBean.error(500,"对不起,您的用户被禁用,请联系管理员");
                        }else if (e instanceof CredentialsExpiredException){
                            error=RespBean.error(500,"对不起,您的用户密码过期,请联系管理员");
                        }else if (e instanceof AccountExpiredException){
                            error=RespBean.error(500,"对不起,您的用户过期,请联系管理员");
                        }else if (e instanceof BadCredentialsException)
                        {
                            error=RespBean.error(500,"对不起,您的用户名或密码错误");
                        }else{
                            error=RespBean.error(500,"未知错误,联系工程师");
                        }
                        writer.print(new ObjectMapper().writeValueAsString(error));
                        writer.flush();
                        writer.close();
                    }
                })
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        RespBean ok=RespBean.ok(200,"注销成功",null);
                        //将对象写成json
                        PrintWriter writer= response.getWriter();
                        writer.print(new ObjectMapper().writeValueAsString(ok));
                        writer.flush();
                        writer.close();
                    }



                })
                //与表单登录相关的接口全放行
                .permitAll()
                .and()
                //防止csrf网络攻击
                .csrf().disable();

    }


}
